
import { _decorator, assetManager, ImageAsset, SpriteFrame, Node, Sprite } from 'cc';
import { HTML5 } from 'cc/env';
const { ccclass, property } = _decorator;

export class ResourceManager {
  // 资源名称
  public static SelfUserHeaderImage = 'SelfUserHeaderImage';
  public static OppoUserHeaderImage = 'OppoUserHeaderImage';
  public static DefaultUserHeaderImage = 'DefaultUserHeaderImage';
  public static GameLevelImage = 'GameLevelImage';
  private static instance: ResourceManager = null as unknown as ResourceManager;
  // 名称 =》 精灵Frame的映射关系
  private mapSpriteFrame = new Map<string, SpriteFrame>;
  public static Instance() {
    if (ResourceManager.instance) {
      return ResourceManager.instance;
    }
    ResourceManager.instance = new ResourceManager();
    return ResourceManager.instance;
  }
  constructor() {

  }
  // 加载图片资源
  loadImageSpriteFrame(name: string, remoteUrl: string, ext?: string) {
    if (HTML5) return; // Web跨域也加载不了，直接返回
    if (!remoteUrl) return;
    const that = this;
    if (ext) {
      assetManager.loadRemote<ImageAsset>(remoteUrl, { ext }, function (err, imageAsset) {
        if (!err) that.mapSpriteFrame.set(name, SpriteFrame.createWithImage(imageAsset));
      });
      return;
    }
    const e = this.getImageExt(remoteUrl);
    assetManager.loadRemote<ImageAsset>(remoteUrl, { e }, function (err, imageAsset) {
      if (!err) that.mapSpriteFrame.set(name, SpriteFrame.createWithImage(imageAsset));
    });
  }

  // 加载图片资源
  setNodeImageSpriteFrame(node: Node, remoteUrl: string) {
    if (HTML5) return; // Web跨域也加载不了，直接返回
    if (!remoteUrl) return;
    const that = this;
    var ext = this.getImageExt(remoteUrl);
    assetManager.loadRemote<ImageAsset>(remoteUrl, { ext }, function (err, imageAsset) {
      if (!err && node) {
        node.getComponent(Sprite).spriteFrame = SpriteFrame.createWithImage(imageAsset);
      }
    });
    return;
  }
  clearSpriteFrame(name: string) {
    this.mapSpriteFrame.delete(name);
  }
  setSpriteFrame(name: string, spf: SpriteFrame) {
    if (spf) {
      this.mapSpriteFrame.set(name, spf);
    }
  }
  getImageSpriteFrame(name: string) {
    var spf = this.mapSpriteFrame.get(name);
    return spf;
  }

  getImageExt(url: string) {
    if (url.endsWith('.png')) return '.png';
    if (url.endsWith('.jpg')) return '.jpg';
    if (url.endsWith('.jpeg')) return '.jpeg';
    return '.jpeg'; // 微信头像默认是jpeg格式
  }
}

